<!DOCTYPE html>
<html>
	<head>
		<title>商品列表</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<!-- CSS & JS Resources -->
		<link rel="stylesheet" href="https://unpkg.com/element-ui@2.13.0/lib/theme-chalk/index.css">
		<link rel="stylesheet" href="../../static/sa.css">
		<style>
			.product-grid {
				display: grid;
				grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
				gap: 20px;
				padding: 20px;
			}
			.product-card {
				border: 1px solid #ebeef5;
				border-radius: 4px;
				overflow: hidden;
				transition: all 0.3s;
				position: relative;
			}
			.product-card:hover {
				box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
				transform: translateY(-2px);
			}
			.product-image {
				height: 200px;
				overflow: hidden;
				position: relative;
			}
			.product-image img {
				width: 100%;
				height: 100%;
				object-fit: cover;
			}
			.product-gallery {
				position: absolute;
				bottom: 10px;
				right: 10px;
				background: rgba(255,255,255,0.9);
				border-radius: 4px;
				padding: 5px;
			}
			.product-gallery img {
				width: 30px;
				height: 30px;
				margin: 0 2px;
				cursor: pointer;
				border: 2px solid transparent;
			}
			.product-gallery img.active {
				border-color: #409EFF;
			}
			.product-content {
				padding: 15px;
			}
			.product-title {
				font-size: 16px;
				font-weight: bold;
				margin-bottom: 10px;
				color: #303133;
			}
			.product-price {
				color: #f56c6c;
				font-size: 20px;
				margin-bottom: 10px;
			}
			.product-meta {
				display: flex;
				justify-content: space-between;
				color: #909399;
				font-size: 13px;
				margin-bottom: 10px;
			}
			.product-attributes {
				margin-top: 10px;
			}
			.attribute-tag {
				margin: 2px;
			}
			.sku-list {
				margin-top: 10px;
				font-size: 13px;
			}
			.filter-section {
				background: #f5f7fa;
				padding: 15px;
				margin-bottom: 20px;
				border-radius: 4px;
			}
			.filter-row {
				margin-bottom: 10px;
			}
			.stock-status {
				position: absolute;
				top: 10px;
				right: 10px;
				z-index: 1;
			}
		</style>
		<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
		<script src="https://unpkg.com/http-vue-loader@1.4.2/src/httpVueLoader.js"></script>
		<script src="https://unpkg.com/element-ui@2.13.0/lib/index.js"></script>
		<script src="https://unpkg.com/jquery@3.4.1/dist/jquery.min.js"></script>
		<script src="https://www.layuicdn.com/layer-v3.1.1/layer.js"></script>
		<script src="../../static/sa.js"></script>
	</head>
	<body>
		<div class="vue-box" style="display: none;" :style="'display: block;'">
			<div class="c-panel">
				<!-- 高级筛选 -->
				<div class="filter-section">
					<el-form ref="form" :model='p' @submit.native.prevent inline>
						<div class="filter-row">
							<el-form-item label="商品名称">
								<el-input v-model="p.name" placeholder="输入商品名称" clearable></el-input>
							</el-form-item>
							<el-form-item label="品牌">
								<el-select v-model="p.brand" placeholder="选择品牌" clearable>
									<el-option v-for="brand in brands" :key="brand" :label="brand" :value="brand"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item label="分类">
								<el-select v-model="p.category" placeholder="选择分类" clearable>
									<el-option v-for="category in categories" :key="category" :label="category" :value="category"></el-option>
								</el-select>
							</el-form-item>
						</div>
						<div class="filter-row">
							<el-form-item label="价格区间">
								<el-input-number v-model="p.minPrice" :min="0" placeholder="最低价"></el-input-number>
								<span style="margin: 0 10px">-</span>
								<el-input-number v-model="p.maxPrice" :min="0" placeholder="最高价"></el-input-number>
							</el-form-item>
							<el-form-item>
								<el-button type="primary" icon="el-icon-search" @click="p.pageNo = 1; f5()">查询</el-button>
								<el-button @click="resetFilters">重置</el-button>
							</el-form-item>
						</div>
					</el-form>
				</div>

				<!-- 商品网格 -->
				<div class="product-grid">
					<div v-for="item in dataList" :key="item.id" class="product-card">
						<!-- 库存状态标签 -->
						<el-tag class="stock-status" :type="item.stock > 0 ? 'success' : 'danger'">
							{{ item.stock > 0 ? '有货' : '缺货' }}
						</el-tag>
						
						<!-- 商品图片 -->
						<div class="product-image">
							<img :src="currentImage(item)" :alt="item.name">
							<div class="product-gallery" v-if="item.images && item.images.length > 1">
								<img v-for="img in item.images" 
									:key="img.image_id" 
									:src="getFullImageUrl(img.image_url)" 
									:class="{'active': img.is_main}"
									@click="setMainImage(item, img)">
							</div>
						</div>

						<!-- 商品内容 -->
						<div class="product-content">
							<div class="product-title">{{ item.name }}</div>
							<div class="product-price">¥{{ item.price.toFixed(2) }}</div>
							<div class="product-meta">
								<span>{{ item.categoryName }}</span>
								<span>{{ item.brandName }}</span>
							</div>
							<div class="product-description">{{ item.description }}</div>

							<!-- 商品属性 -->
							<div class="product-attributes">
								<el-tag v-for="attr in item.attributes" 
									:key="attr.attribute_id"
									size="mini"
									class="attribute-tag">
									{{ attr.attribute_name }}: {{ attr.attribute_value }}
								</el-tag>
							</div>

							<!-- SKU列表 -->
							<el-collapse v-if="item.skus && item.skus.length > 0">
								<el-collapse-item title="规格选项">
									<div class="sku-list">
										<div v-for="sku in item.skus" :key="sku.sku_id">
											<span>{{ sku.sku_code }}</span>
											<span style="float: right">
												¥{{ sku.sku_price.toFixed(2) }}
												<el-tag size="mini" :type="sku.sku_stock > 0 ? 'success' : 'danger'">
													库存: {{ sku.sku_stock }}
												</el-tag>
											</span>
										</div>
									</div>
								</el-collapse-item>
							</el-collapse>

							<!-- 操作按钮 -->
							<div style="margin-top: 15px">
								<el-button type="text" @click="get(item)">查看详情</el-button>
								<el-button type="text" @click="update(item)">编辑</el-button>
								<el-button type="text" style="color: #f56c6c" @click="del(item)">删除</el-button>
							</div>
						</div>
					</div>
				</div>

				<!-- 分页 -->
				<div style="text-align: center; margin-top: 20px">
					<el-pagination
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page="p.pageNo"
						:page-sizes="[10, 20, 30, 40]"
						:page-size="p.pageSize"
						layout="total, sizes, prev, pager, next, jumper"
						:total="dataCount">
					</el-pagination>
				</div>
			</div>
		</div>
		<script>
			var app = new Vue({
				components: {
					"sa-item": httpVueLoader('../../sa-frame/com/sa-item.vue'),		
					"sa-td": httpVueLoader('../../sa-frame/com/sa-td.vue'),			
				},
				el: '.vue-box',
				data: {
					p: {
						name: '',
						brand: '',
						category: '',
						minPrice: null,
						maxPrice: null,
						pageNo: 1,
						pageSize: 10,
					},
					dataCount: 0,
					dataList: [],
					brands: [],
					categories: [],
					imageCache: {},
					baseImageUrl: 'http://8.134.184.130:8008/images/' // 基础图片URL
				},
				methods: {
					// 刷新数据
					f5: function() {
						var params = {
							pageNo: this.p.pageNo,
							pageSize: this.p.pageSize
						};
						
						// 添加非空筛选条件
						if (this.p.name) params.name = this.p.name;
						if (this.p.brand) params.brand = this.p.brand;
						if (this.p.category) params.category = this.p.category;
						if (this.p.minPrice !== null) params.minPrice = this.p.minPrice;
						if (this.p.maxPrice !== null) params.maxPrice = this.p.maxPrice;

						$.ajax({
							url: 'http://localhost:8080/product/listProductAggregation',
							type: 'GET',
							data: params,
							success: function(res) {
								console.log(res);
								if (res.code === 200) {
									this.dataList = res.data.list || [];
									this.dataCount = res.data.total || 0;
									this.p.pageNo = res.data.pageNum || 1;
									
									// Extract unique brands and categories
									this.brands = [...new Set(this.dataList.map(item => item.brandName))];
									this.categories = [...new Set(this.dataList.map(item => item.categoryName))];
								} else {
									this.$message.error('获取数据失败：' + res.message);
								}
							}.bind(this),
							error: function(xhr, status, error) {
								this.$message.error('请求失败：' + error);
							}.bind(this)
						});
					},

					// 重置筛选条件
					resetFilters: function() {
						this.p.name = '';
						this.p.brand = '';
						this.p.category = '';
						this.p.minPrice = null;
						this.p.maxPrice = null;
						this.p.pageNo = 1;
						this.f5();
					},

					// 图片处理
					currentImage: function(item) {
						if (!item.images || item.images.length === 0) return '';
						const mainImage = item.images.find(img => img.is_main);
						const imageUrl = mainImage ? mainImage.image_url : item.images[0].image_url;
						return this.getFullImageUrl(imageUrl);
					},

					getFullImageUrl: function(imageUrl) {
						if (!imageUrl) return '';
						// 如果URL已经以http://或https://开头，直接返回
						if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
							return imageUrl;
						}
						// 移除开头的斜杠以避免双斜杠
						const cleanUrl = imageUrl.startsWith('/') ? imageUrl.substring(1) : imageUrl;
						return this.baseImageUrl + cleanUrl;
					},

					setMainImage: function(item, image) {
						item.images.forEach(img => img.is_main = (img.image_id === image.image_id));
					},

					// 分页处理器
					handleSizeChange: function(val) {
						this.p.pageSize = val;
						this.f5();
					},

					handleCurrentChange: function(val) {
						this.p.pageNo = val;
						this.f5();
					},

					// 增删改查操作
					get: function(data) {
						sa.showIframe('商品详情', 'product-info.html?id=' + data.id, '800px', '600px');
					},

					update: function(data) {
						sa.showIframe('修改商品', 'product-edit.html?id=' + data.id, '800px', '600px');
					},

					del: function(data) {
						this.$confirm('是否删除该商品？此操作不可撤销', '提示', {
							type: 'warning'
						}).then(() => {
							$.ajax({
								url: 'http://localhost:8080/product/deleteProduct?productId=' + data.id,
								type: 'POST',
								success: function(res) {
									if (res.code === 200) {
										this.dataList = this.dataList.filter(item => item.id !== data.id);
										this.$message.success('删除成功');
									} else {
										this.$message.error('删除失败：' + res.message);
									}
								}.bind(this),
								error: function(xhr, status, error) {
									this.$message.error('请求失败：' + error);
								}.bind(this)
							});
						}).catch(() => {});
					}
				},
				created: function() {
					this.f5();
				}
			})
		</script>
	</body>
</html>
